﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Xml;
using System.Xml.Serialization;

namespace Chenglin.WPChildrenDrug.Models
{
    public class DrugInfoItem
    {
        [XmlAttribute("key")]
        public string Name { get; set; }

        [XmlText]
        public string Value { get; set; }
    }

    /// <summary>
    /// Describes the information for a specific drug.
    /// </summary>
    public class DrugEntry
    {
        [XmlAttribute("name")]
        public string Name { get; set; }

        /// <summary>
        /// The location where the information was read.
        /// </summary>
        [XmlAttribute("url")]
        public string SourceUrl { get; set; }

        [XmlAttribute("approvalNumber")]
        public string ApprovalNumber { get; set; }

        [XmlAttribute("producer")]
        public string Manufacturer { get; set; }

        [XmlElement("a")]
        public DrugInfoItem[] Items { get; set; }
    }

    [XmlRoot("drug")]
    public class Drug
    {
        [XmlAttribute("name")]
        public string Name { get; set; }

        [XmlElement("entry")]
        public DrugEntry[] Entries { get; set; }

        /// <summary>
        /// Read drugs from the resource file.
        /// </summary>
        public static DrugData ReadDrugList()
        {
            Uri uri = new Uri("Resources/Drugs.xml", UriKind.Relative);
            using (var stream = Application.GetResourceStream(uri).Stream)
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(Drug));
                List<Drug> list = new List<Drug>();
                using (var xr = XmlReader.Create(stream))
                {
                    while (xr.Read())
                    {
                        if (xr.NodeType == XmlNodeType.Element && xr.Name == "drug")
                        {
                            list.Add((Drug)xmlSerializer.Deserialize(xr.ReadSubtree()));
                        }
                    }
                }

                return new DrugData(list.ToArray());
            }
        }
    }
}
